package com.dingding.service.user.facade.reg;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.District;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.facade.user.service.reg.IUserRegFacade;
import com.dingding.facade.user.service.reg.code.RegSourceEnum;
import com.dingding.facade.user.service.reg.code.RegUserEnum;
import com.dingding.facde.coupon.ICouponService;
import com.dingding.service.user.core.dao.IWechatUserDao;

/**
 * @Description:用户注册
 * @author fengshuonan
 * @date 2016年6月28日 上午11:50:04
 * @version 叮叮搭车
 */
@Component("userRegFacade")
public class UserRegFacadeImpl implements IUserRegFacade{

	@Autowired
	private IUserInfoFacade userInfoFacade;   //用户信息接口
	
	@Autowired
	private IWechatUserDao wechatUserDao;	  //微信用户dao
	
	@Autowired
	private ICouponService couponService;		//优惠券接口
	
	/**
	 * @Description:注册用户并根据注册地点（北京或唐山）赠送优惠券
	 * @param tellphone 电话号码
	 * @param openId 微信的openid
	 * @author fengshuonan
	 * @return String 注册地点 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public RegUserEnum regUserAndGiveCoupons(String tellphone, String openId) {
		
		//验证参数是否为空
		if(ToolUtil.validateParas(tellphone, openId)){
			return RegUserEnum.PARA_NULL;
		}
		
		/**
		 * 1.添加用户
		 */
		//判断是否注册
		boolean isReg = this.userInfoFacade.userIsRegedByPhone(tellphone);
		
		if(isReg){
			return RegUserEnum.ALREADY_REG;
		}
		
		//添加用户
		this.userInfoFacade.addUser(tellphone, openId);
		
		
		/**
		 * 2.根据用户关注微信公众号的来源，为用户添加相应的优惠券
		 * 
		 * 如果来源所属区域为北京，添加洗车券和搭车现金券   
		 * 如果来源所属区域为唐山，添加搭车现金券		 
		 */
		//查找这个用户关注微信公众号的来源
		String promotionId = this.wechatUserDao.getPromotionIdByWechatId(openId);
		
		if(ToolUtil.isBlank(promotionId)){
			return RegUserEnum.NO_FROM_CITY;
		}
		
		//根据查找到的推广号id获取所属区域id
		District district = this.couponService.getDistrictByDistrictId(promotionId);
		
		if(district == null){
			return RegUserEnum.NO_FROM_CITY;
		}
		
		Integer districtId = district.getCityName();
		if(districtId == null || districtId == 0){
			return RegUserEnum.NO_FROM_CITY;
		}
		
		//如果来源为北京，则赠送洗车券和现金券
		if(RegSourceEnum.BEIJING.getCode() == districtId){
			this.couponService.addCarWashCouponAndMoneyCoupon(tellphone);
			return RegUserEnum.FROM_CITY_IS_BEIJING;
		}
		
		//如果来源为唐山，赠送现金券
		if(RegSourceEnum.TANGSHAN.getCode() == districtId){
			this.couponService.addMoneyCoupon(tellphone);
			return RegUserEnum.FROM_CITY_IS_TANGSHAN;
		}
		
		return RegUserEnum.FROM_CITY_IS_OTHERS;
	}

}
